<template>
  <div class="login-wrap">
    <div class="login-content">
      <div class="login-title">系统登录</div>
      <el-form ref="loginFormRef" class="login-form" :model="param" :rules="rules" status-icon>
        <el-form-item prop="username">
          <el-input class="input-user" v-model="param.username" placeholder="用户名">
            <template #prepend>
              <div>
                <el-icon class="input-icon"><avatar /></el-icon>
              </div>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="param.password" placeholder="密码" :type="passwordType" @keyup.enter="submitForm">
            <template #prepend>
              <!-- <i v-show="passwordLock" class="el-icon-lock" @click="switchPass" />
              <i v-show="!passwordLock" class="el-icon-unlock" @click="switchPass" /> -->
              <el-icon><unlock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <div class="login-btn">
          <el-button type="primary" :loading="btnLoading" @click="submitForm">登录</el-button>
        </div>
        <!-- <p class="login-tips">用户名: admin 密码: 123</p>
        <p class="login-tips">用户名: editor 密码: 456</p> -->
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { Avatar, Unlock } from '@element-plus/icons-vue'
import { sm2 } from 'sm-crypto'
import md5 from 'md5'
import moment from 'moment'
import request from 'Common/request/index.js'

import fetch from 'isomorphic-fetch'

let keypair = sm2.generateKeyPairHex()

// let publicKey = keypair.publicKey // 公钥
let publicKey =
  '047214fe3a249b75b6ba92ee494e0a8a68c0a19893a480b3c28bf06cd5b7d621243c7f6704caa3b43ade6be15de11cabd185611a9edfdcf1b11d7a2478c67b4c1c'
let privateKey = keypair.privateKey // 私钥

const router = useRouter()
const store = useStore()

const btnLoading = ref(false)
const loginFormRef = ref(null)
const passwordLock = ref(true)
const passwordType = ref('password')

const param = reactive({
  username: '',
  password: ''
})

const rules = reactive({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
})

const generateCharacter = (n) => {
  var chars = [
    '0',
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    'A',
    'B',
    'C',
    'D',
    'E',
    'F',
    'G',
    'H',
    'I',
    'J',
    'K',
    'L',
    'M',
    'N',
    'O',
    'P',
    'Q',
    'R',
    'S',
    'T',
    'U',
    'V',
    'W',
    'X',
    'Y',
    'Z'
  ]
  var res = ''
  for (var i = 0; i < n; i++) {
    var id = Math.ceil(Math.random() * 35)
    res += chars[id]
  }

  return res
}

const getCurrentDay = () => {
  let date = ''
  date = moment(new Date()).format('YYYYMMDD')
  return date
}

const switchPass = () => {
  if (passwordLock.value) {
    passwordType.value = 'text'
  } else {
    passwordType.value = 'password'
  }
  passwordLock.value = !passwordLock.value
}

const submitForm = () => {
  let salt = ''
  salt = generateCharacter(16)
  // sessionStorage.setItem("token", "123123")
  // router.push('/')
  loginFormRef.value.validate((valid) => {
    // console.log('paramssss', param);
    if (valid) {
      // btnLoading.value = true
      // 访问登录接口
      let salt = ''
      let date = ''
      let key = ''
      let sign = ''
      let password = ''
      let account = ''

      salt = generateCharacter(16)
      console.log('validate-salt', salt)
      date = getCurrentDay()
      console.log('validate-date', date)
      password = sm2.doEncrypt(param.password + salt, publicKey, 1)
      account = sm2.doEncrypt(param.username.trim() + salt, publicKey, 1)

      password = '04' + password
      account = '04' + account

      if (salt && date) {
        key = salt + date
        console.log('validate-key', key)
      }
      sign = 'account=' + account + '&password=' + password + '&salt=' + salt + '&key=' + key

      let parms = {
        account,
        password,
        salt: salt,
        sign: md5(sign),
        languageCode: sessionStorage.getItem('lang') || null //用户选择的语种，否则为null
      }

      let url = 'https://test-fulanedu-mg.fairyclass.cn/system/api/loginManage'
      let paramv = {
        method: 'post',
        data: parms
      }
      request(url, paramv).then((response) => {
        // debugger
        if (response.code == 1000) {
          sessionStorage.setItem('token', response.data.Authorization)
          router.push('/')
        } else {
          ElMessage.error(response.subMsg)
        }
      })
    } else {
      ElMessage.error('请输入用户名和密码')
    }
  })
}
</script>

<style lang="less" scoped>
.login-wrap {
  position: relative;
  width: 100%;
  height: 100vh;
  background-color: #235bae;
  // background-image: url(/img/login_bg.jpg);
  background-image: url(./imgs/builds.bud.jpg);
  background-size: cover;
}

.login-title {
  width: 100%;
  font-size: 20px;
  line-height: 50px;
  color: #fff;
  text-align: center;
  border-bottom: 1px solid #ddd;
}

.login-content {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 350px;
  margin: -190px 0 0 -175px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.4);
  border-radius: 5px;
}

.login-form {
  padding: 30px;
  .el-input-group {
    padding-left: 10px !important;
    padding-right: 10px !important;
    padding: 0 10px !important;
  }
}

.login-btn {
  text-align: center;
}

.login-btn button {
  width: 100%;
  height: 36px;
  margin-bottom: 10px;
}

.login-tips {
  font-size: 12px;
  line-height: 30px;
  color: #be1480;
}

.el-icon-lock,
.el-icon-unlock {
  cursor: pointer;
}
</style>
